from remote_ssh import Client
from loguru import logger

logger.add("ssh_remote_connetc.log", level="INFO", rotation="1 week", retention="10 days")

"""
get angle and agnes server status (idle or busy)
"""
def get_server_status(hostname, username="sdc"):
    
    data ={}
    try:
        server = Client(hostname=hostname, username=username)

        cmd_createUSB = "ps -ef | grep -v grep | grep createUSB | head -1 "
        res1 = server.exec_command(cmd_createUSB)
        if res1:
            data["status"] = "busy"
            pid = server.exec_command(cmd_createUSB + "| awk '{print $2}'")
            data["pid"] = pid
            cmd_time = f"ps -o etimes -p {pid} | tail -1"
            res_time = server.exec_command(cmd_time)
            mins = str(int(res_time) / 60)
            seds = str(int(res_time) % 60)
            duration = mins + "分" + seds + "秒"
            data["duration"] = duration
            data["task"] = server.exec_command(cmd_createUSB + "| awk '{print $9, $10, $11}'")
            return data
        else:
            data["status"] = "idle"

        cmd_dd = "ps -ef | grep -v grep | grep '=/dev/sd' | head -1 "
        res2 = server.exec_command(cmd_dd)
        if res2:
            data["status"] = "busy"
            pid = server.exec_command(cmd_dd + "| awk '{print $2}'")
            data["pid"] = pid
            cmd_time = f"ps -o etime -p {pid} | tail -1"
            data["duration"] = server.exec_command(cmd_time)
            data["task"] = server.exec_command(cmd_dd + "| awk '{print $9, $10, $11, $12}'")
        else:
            data["status"] = "idle"
        return data

    except Exception as e:
        logger.error(e)
    finally:
        server.close()
